//打包优化，参考https://blog.csdn.net/qq_35556763/article/details/145276063?spm=1001.2014.3001.5502

//分片打包
const TerserPlugin = require('terser-webpack-plugin')
//gzip压缩
const CompressionPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = /\.(js|css|json|txt|ico|svg)(\?.*)?$/i
const path = require('path')

function resolve (dir) {
  return path.join(__dirname, dir)
}

module.exports = {
  //路径前缀
  publicPath: '/',
  lintOnSave: true,
  productionSourceMap: false,
  chainWebpack: config => {
    //新增gzip压缩
    config.resolve.alias.set('@', resolve('src'))
    // 在生产环境下应用 CompressionPlugin
    if (process.env.NODE_ENV === 'production') {
      config.plugin('compressionPlugin').use(
        new CompressionPlugin({
          filename: '[path].gz[query]', // 目标文件名
          algorithm: 'gzip', // 压缩算法
          test: productionGzipExtensions, // 满足正则表达式的文件会被压缩
          threshold: 10240, // 只处理比这个值大的资源。按字节计算 10240=10KB
          minRatio: 0.8, // 只有压缩率比这个值小的资源才会被处理
          deleteOriginalAssets: false // 是否删除原资源
        })
      )
    }
  },

  configureWebpack: {
    //分片打包
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            ecma: undefined,
            warnings: false,
            parse: {},
            compress: {
              drop_console: true,
              drop_debugger: true,
              pure_funcs: ['console.log'] // 移除console
            }
          }
        })
      ],
      runtimeChunk: 'single',
      splitChunks: {
        chunks: 'all',
        maxInitialRequests: Infinity,
        minSize: 20000,
        cacheGroups: {
          vendor: {
            test: /[\\/]node_modules[\\/]/
          }
        }
      }
    }
  },
  css: {
    extract: { ignoreOrder: true }
  },
  //开发模式反向代理配置，生产模式请使用Nginx部署并配置反向代理
  //20254-12-25 注意安装插件：npm install v-scale-screen@1.0.0 --save-dev
  devServer: {
    port: 8080,
    proxy: {
      '/api': {
        //本地服务接口地址
        target: 'http://127.0.0.1:8048',
        // target: 'http://192.168.2.246:8083',
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': '/'
        }
      }
    }
  }
}
